package cn.taobaoke.restful.service;

import cn.taobaoke.restful.exception.TBKException;
import cn.taobaoke.restful.util.GsonUtil;
import cn.taobaoke.restful.util.OkHttpUtil;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * InnerService类.
 * +-----------------------------------------------------------------------------------------------+
 * |类名称: InnerAPIService                                                                         |
 * |创建时间: 6/24/17                                                                               |
 * |功能简介:                                                                                       |
 * |参考链接:                                                                                       |
 * +-----------------------------------------------------------------------------------------------+
 *
 * @author luch
 */
@Service
public class InnerAPIService {

    private static final String SHORT_SERVER_HOST = "http://47.93.227.191:8181";

    /**
     * 使用邀请码
     *
     * @param code
     * @return
     */
    public boolean useInviteCode(String code) throws IOException {
        String host = "http://127.0.0.1:9111/tkb/api/code/use?code=" + code;

        String json = OkHttpUtil.DEFAULT.get(host);
        Map map = GsonUtil.getObject(json);

        Boolean success = (Boolean) map.get("success");
        if (success != null && success) {
            return (boolean) map.get("data");
        } else {
            throw new TBKException((String) map.get("msg"));
        }
    }


    public String shortLink(String detailUrl) throws IOException {
        String shortLinkAPI = String.format("%s/cwl/link/lslink", SHORT_SERVER_HOST);
        Map param = new HashMap();
        param.put("llink", detailUrl);

        String ret = OkHttpUtil.DEFAULT.postJson(shortLinkAPI, GsonUtil.getJsonString(param));
        if (ret == null || ret.trim().isEmpty()) {
            throw new TBKException("生成短连接");
        }
        Map map = GsonUtil.getObject(ret);
        Boolean success = (Boolean) map.get("success");
        if (success == null || !success) {
            throw new TBKException((String) map.get("message"));
        }
        return (String) map.get("data");
    }

    public String productToApplyPlan(Integer productId, String couponUrl, String identity) throws IOException {
        String planAPI = String.format("%s/cwl/goods/tbkshare", SHORT_SERVER_HOST);
        Map param = new HashMap();
        param.put("id", productId);
        param.put("couponUrl", couponUrl);
        param.put("pid", identity);
        return OkHttpUtil.DEFAULT.postJson(planAPI, GsonUtil.getJsonString(param));
    }


}
